import socket
try:
	import win32com
	import win32com.client
except:
	print("No win32com module found. uPnP will not work.")

port = 6666

try:
	natter = win32com.client.Dispatch("HNetCfg.NATUPnP")
	mappingPorts = natter.StaticPortMappingCollection
	mappingPorts.Add(port, "UDP", port, socket.gethostbyname(socket.gethostname()), True, "ExegesisServer")
except:
	print("Setting up uPnP failed.")


def ed(data):
	return bytes(str(data), 'UTF-8')

def dd(data):
	return eval(data.decode('UTF-8'))


print("Binding socket")
sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
sock.bind( ("", port) )
#sock.settimeout(0.0)

print("Awaiting a connection")
(data, addr) = sock.recvfrom(2048)
data = dd(data)
print(data)
if(data):
	print("Connection from " + str(addr) + ". Sending response.")
	sock.sendto( ed(str({"type":"sup"})), (addr[0], addr[1]) )
